package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.BusinessRuleUserPermissionHelp;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.ClueJointRecheckEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.ClueJointRecheckModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ClueJointRecheckCustomerAndContactPojo;
import com.xbongbong.paas.pojo.ClueJointRecheckRulePojo;
import com.xbongbong.paas.pojo.ClueRecheckFormPojo;
import com.xbongbong.paas.pojo.ClueRecheckJointRulePojo;
import com.xbongbong.paas.pojo.RecheckJointClueAttrPojo;
import com.xbongbong.paas.pojo.RecheckJointLinkAttrPojo;
import com.xbongbong.paas.pojo.RecheckRuleFromDbPojo;
import com.xbongbong.paas.service.ClueJointRecheckService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.dto.ClueJointRecheckCustomerAttrDTO;
import com.xbongbong.pro.form.pojo.dto.FormClueJointRecheckDTO;
import com.xbongbong.pro.form.pojo.dto.FormClueJointRecheckSaveDTO;
import com.xbongbong.pro.form.pojo.vo.ClueJointRecheckCustomerAttrVO;
import com.xbongbong.pro.form.pojo.vo.FormClueJointRecheckAllRuleVO;
import com.xbongbong.pro.form.pojo.vo.FormClueJointRecheckVO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.log.pojo.DuplicateClueLinkPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lrj
 * @date 2021/11/25 15:16
 */
@Service("clueJointRechekService")
public class ClueJointRechekServiceImpl implements ClueJointRecheckService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResultShowRuleServiceImpl.class);


    @Resource
    private ClueJointRecheckModel clueJointRecheckModel;
    @Resource
    private BusinessRuleUserPermissionHelp businessRuleUserPermissionHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private LogHelp logHelp;

    @Resource
    private MongoLogHelp mongoLogHelp;

    public static List<Integer> getClueJointRecheckAttr(){
        // 1. 线索联合查重只支持单行文本类型字段,子表单类型的也不需要移除，需要判断子表单中是否有单行文本
        return Arrays.asList(FieldTypeEnum.TEXT.getType(), FieldTypeEnum.SUB_FORM.getType(), FieldTypeEnum.CONTACT_NUMBER.getType());
    }

    /**
     * 返回线索和联系人的可选字段，以及客户的所有表单模版数据
     * @param formClueJointRecheckDTO
     * @return
     * @throws XbbException
     */
    @Override
    public FormClueJointRecheckVO getAllAttr(FormClueJointRecheckDTO formClueJointRecheckDTO) throws XbbException {
        Long formId = formClueJointRecheckDTO.getFormId();
        String corpid = formClueJointRecheckDTO.getCorpid();
        Integer businessType = formClueJointRecheckDTO.getBusinessType();
        FormClueJointRecheckVO formClueJointRecheckVO = new FormClueJointRecheckVO();
        try{
            //获得线索的所有可选字段
            List<RecheckJointLinkAttrPojo> clueChoose = getClueChoose(corpid,businessType,formId);
            //获得可选的所有的客户模版
            int customerCode = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
            formClueJointRecheckDTO.setBusinessType(customerCode);
            List<ClueRecheckFormPojo> customerTemplate = getTemplate(formClueJointRecheckDTO);
            //获得联系人的所有可选择字段
            //获得联系人的businessType
            int code = XbbRefTypeEnum.CONTACT.getCode();
            formClueJointRecheckDTO.setBusinessType(code);
            List<ClueRecheckFormPojo> contactTemplate = getTemplate(formClueJointRecheckDTO);
            ClueRecheckFormPojo clueRecheckFormPojo = contactTemplate.get(0);
            //获得联系人的可选字段
            List<RecheckJointLinkAttrPojo> contactChoose = getClueChoose(corpid, clueRecheckFormPojo.getBusinessType(), clueRecheckFormPojo.getFormId());
            formClueJointRecheckVO.setClueAttrList(clueChoose);
            formClueJointRecheckVO.setCustomerFormList(customerTemplate);
            formClueJointRecheckVO.setContactAttrList(contactChoose);
        }catch (Exception e){
            LOGGER.error("ClueJointRechekServiceImpl.getAllAttr出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formClueJointRecheckVO;
    }

    /**
     * 获得表单模板
     * @return
     */
    public  List<ClueRecheckFormPojo> getTemplate(FormClueJointRecheckDTO formClueJointRecheckDTO) throws XbbException{
        Map<String, java.lang.Object> map = null;
        List<PaasFormEntityExt> paasFormEntityList = new ArrayList<>();
        List<ClueRecheckFormPojo> clueRecheckFormPojoList = new ArrayList<>();
        try {
            map = BeanUtil.convertBean2Map(formClueJointRecheckDTO,true);
            map.put("del", DelEnum.NORMAL.getDel());
            map.put("hidden", 0);
            map.put("distributorMark", 0);
            map.remove("formId");
            paasFormEntityList = paasFormModel.list(map);
            if (CollectionsUtil.isEmpty(paasFormEntityList)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formClueJointRecheckDTO.getBusinessType());
            switch(xbbRefTypeEnum){
                case CUSTOMER_MANAGEMENT:
                    ClueRecheckFormPojo clueRecheckFormPojoAll = new ClueRecheckFormPojo();
                    clueRecheckFormPojoAll.setFormId(null);
                    clueRecheckFormPojoAll.setForm("all");
                    clueRecheckFormPojoAll.setFormName(OperateModuleTypeEnum.DUPLICATE_ALL_TEMPLATE.getName());
                    clueRecheckFormPojoAll.setIsAll(1);
                    clueRecheckFormPojoList.add(clueRecheckFormPojoAll);
                    for (PaasFormEntityExt paasFormEntityExt : paasFormEntityList){
                        ClueRecheckFormPojo clueRecheckFormPojo = new ClueRecheckFormPojo();
                        clueRecheckFormPojo.setFormId(paasFormEntityExt.getId());
                        clueRecheckFormPojo.setFormName(paasFormEntityExt.getName());
                        clueRecheckFormPojo.setBusinessType(paasFormEntityExt.getBusinessType());
//                        if(Objects.equals(BasicConstant.ONE, paasFormEntityExt.getEnable())){
//                            //只有处于启用状态的表单模板才返回
//                            clueRecheckFormPojoList.add(clueRecheckFormPojo);
//                        }
                        clueRecheckFormPojoList.add(clueRecheckFormPojo);
                    }
                    break;
                case CONTACT:
                    for (PaasFormEntityExt paasFormEntityExt : paasFormEntityList){
                        ClueRecheckFormPojo clueContactRecheckFormPojo = new ClueRecheckFormPojo();
                        clueContactRecheckFormPojo.setFormId(paasFormEntityExt.getId());
                        clueContactRecheckFormPojo.setFormName(paasFormEntityExt.getName());
                        clueContactRecheckFormPojo.setBusinessType(paasFormEntityExt.getBusinessType());
                        clueRecheckFormPojoList.add(clueContactRecheckFormPojo);
                    }
                    break;
                default:
                    break;
            }

        } catch (XbbException e) {
            LOGGER.error("ClueJointRechekServiceImpl.getTemplate出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return clueRecheckFormPojoList;
    }

    /**
     * 获得所有的线索和联系人可查重的字段
     * @param corpid
     * @param corpid
     * @return
     */
    public List<RecheckJointLinkAttrPojo> getClueChoose(String corpid, Integer businessType, Long formId) throws XbbException {

        try{
//            List<RecheckJointLinkAttrPojo> recheckJointLinkAttrPojoList = new ArrayList<>();
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //获得公司版本
            Integer feeType = businessRuleUserPermissionHelp.getFeeType(corpid);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            //判断是线索还是联系人
            switch(xbbRefTypeEnum){
                case CLUE:
//                    Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
                    //判断当前公司是旗舰版还是高级版
                    // 将高级版、旗舰版的区别去掉，高级版改为由前端处理
//                    if(Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType)){
//                        explainList.forEach((item) -> explainMap.put(item.getAttr(), item));
//                        //高级版,只有线索的企业名称和线索电话字段可以设置联合查重
//                        String nameAttr = ClueEnum.COMPANY_NAME.getAttr();
//                        String phoneAttr = ClueEnum.PHONE.getAttr();
//                        //判断这两个字段在表单模板中是否是处于未启用或回收站，或者是否没有开启不允许重复值
//                        //名称字段
//                        FieldAttrEntity fieldAttrEntity = explainMap.get(nameAttr);
//                        //名称字段处于启用状态，并且开启了不允许重复值
//                        boolean flag = Objects.nonNull(fieldAttrEntity) && Objects.equals(BasicConstant.ONE, fieldAttrEntity.getIsOpen()) &&
//                                Objects.equals(BasicConstant.ONE, fieldAttrEntity.getNoRepeat());
//                        if(flag){
//                            //名称字段符合条件，把出名称和电话外的字段移除
//                            explainList.removeIf(item -> !Objects.equals(nameAttr, item.getAttr()) && !Objects.equals(phoneAttr, item.getAttr()));
//                        }else {
//                            //不是电话字段移除
//                            explainList.removeIf(item -> !Objects.equals(phoneAttr, item.getAttr()));
//                        }
//                        List<RecheckJointLinkAttrPojo> formExplainList = clueAndContactResultDeal(explainList, businessType);
//                        return formExplainList;
//                    }else if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)){
//                        //旗舰版
//                        //线索联合查重只支持单行文本类型字段（包含子表单中的单行文本），并且只有勾选了不允许重复值的数据才能去关联客户或联系人字段
//                        List<Integer> clueJointRecheckAttr = getClueJointRecheckAttr();
//                        //单行文本并且没有开启不允许重复值才移除
//                        //将隐藏字段去除
//                        //回收站或未启用字段移除
//                        explainList.removeIf(item -> !clueJointRecheckAttr.contains(item.getFieldType()) ||
//                                    (Objects.equals(FieldTypeEnum.TEXT.getType(), item.getFieldType()) && Objects.equals(BasicConstant.ZERO, item.getNoRepeat())) ||
//                                Objects.equals(BasicConstant.ONE, item.getEditHide()) ||
//                                Objects.equals(BasicConstant.ZERO, item.getIsOpen()) ||
//                                Objects.equals(BasicConstant.TWO, item.getIsOpen()));
//                    }

                    //线索联合查重只支持单行文本类型字段（包含子表单中的单行文本），并且只有勾选了不允许重复值的数据才能去关联客户或联系人字段
                    List<Integer> clueJointRecheckAttr = getClueJointRecheckAttr();
                    //单行文本并且没有开启不允许重复值才移除
                    //将隐藏字段去除
                    //回收站或未启用字段移除
                    explainList.removeIf(item -> !clueJointRecheckAttr.contains(item.getFieldType()) ||
                            (Objects.equals(FieldTypeEnum.TEXT.getType(), item.getFieldType()) && Objects.equals(BasicConstant.ZERO, item.getNoRepeat())) ||
                            Objects.equals(BasicConstant.ONE, item.getEditHide()) ||
                            Objects.equals(BasicConstant.ZERO, item.getIsOpen()) ||
                            Objects.equals(BasicConstant.TWO, item.getIsOpen()));
                    break;
                case CONTACT:
                    //线索联合查重只支持单行文本类型字段（包含子表单中的单行文本），联系人是被选择字段不需要添加勾选不可重复值这个选项
                    List<Integer> contactJointRecheckAttr = getClueJointRecheckAttr();
                    //单行文本并且没有开启不允许重复值才移除
                    //将隐藏字段去除
                    //回收站或未启用字段移除
                    explainList.removeIf(item -> !contactJointRecheckAttr.contains(item.getFieldType()) ||
                            Objects.equals(BasicConstant.ONE, item.getEditHide()) ||
                            Objects.equals(BasicConstant.ZERO, item.getIsOpen()) ||
                            Objects.equals(BasicConstant.TWO, item.getIsOpen()));
                default:
                    break;
            }
            List<RecheckJointLinkAttrPojo> formExplainList = clueAndContactResultDeal(explainList, businessType);
            return formExplainList;
        }catch (Exception e){
            LOGGER.error("ClueJointRechekServiceImpl.getClueChoose出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    /**
     * 名称和电话字段的处理
     * @param explainList
     * @return
     */
    private List<RecheckJointLinkAttrPojo> clueAndContactResultDeal(List<FieldAttrEntity> explainList, Integer businessType){
        List<RecheckJointLinkAttrPojo> recheckJointLinkAttrPojoList = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : explainList){
            //还需要考虑子表单中的单行文本
            boolean flag = Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.SUB_FORM.getType())
                    ||  Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.CONTACT_NUMBER.getType()));
            if (flag) {
                SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                if (Objects.nonNull(subForm) && CollectionsUtil.isNotEmpty(subForm.getItems())) {
                    List<? extends FieldAttrEntity> items = subForm.getItems();
                    for (FieldAttrEntity item : items) {
                        //单行文本处于启用状态，并且开启了不允许重复值
                        boolean textFlag = false;
                        if (Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())){
                            textFlag = Objects.equals(item.getIsOpen(),BasicConstant.ONE) && Objects.equals(item.getFieldType(),FieldTypeEnum.TEXT.getType());
                        }else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                            textFlag = Objects.equals(item.getIsOpen(),BasicConstant.ONE) && Objects.equals(item.getFieldType(),FieldTypeEnum.TEXT.getType());
                        } else {
                            textFlag = Objects.equals(item.getIsOpen(),BasicConstant.ONE) && Objects.equals(item.getFieldType(),FieldTypeEnum.TEXT.getType()) &&
                                    Objects.equals(item.getNoRepeat(), BasicConstant.ONE);
                        }
                        if (textFlag) {
                            RecheckJointLinkAttrPojo clueRecheckContactLinkPojo = new RecheckJointLinkAttrPojo();
                            clueRecheckContactLinkPojo.setFieldId(item.getFieldId());
                            clueRecheckContactLinkPojo.setAttr(fieldAttrEntity.getAttr() + "." + item.getAttr());
                            clueRecheckContactLinkPojo.setAttrName(fieldAttrEntity.getAttrName()  + "." + item.getAttrName());
                            clueRecheckContactLinkPojo.setFieldType(item.getFieldType());
                            clueRecheckContactLinkPojo.setIsRedundant(item.getIsRedundant());
                            recheckJointLinkAttrPojoList.add(clueRecheckContactLinkPojo);
                        }
                    }
                }
            }else{
                RecheckJointLinkAttrPojo clueRecheckContactLinkPojo = new RecheckJointLinkAttrPojo();
                clueRecheckContactLinkPojo.setAttr(fieldAttrEntity.getAttr());
                clueRecheckContactLinkPojo.setAttrName(fieldAttrEntity.getAttrName());
                clueRecheckContactLinkPojo.setFieldId(fieldAttrEntity.getFieldId());
                clueRecheckContactLinkPojo.setFieldType(fieldAttrEntity.getFieldType());
                clueRecheckContactLinkPojo.setIsRedundant(fieldAttrEntity.getIsRedundant());
                recheckJointLinkAttrPojoList.add(clueRecheckContactLinkPojo);
            }
        }
        return recheckJointLinkAttrPojoList;
    }

    /**
     * 获得客户已经设置的联合查重规则
     * @param formClueJointRecheckDTO
     * @return
     * @throws XbbException
     */
    @Override
    public FormClueJointRecheckAllRuleVO get(FormClueJointRecheckDTO formClueJointRecheckDTO) throws XbbException {
        Long formId = formClueJointRecheckDTO.getFormId();
        String corpid = formClueJointRecheckDTO.getCorpid();
        //获得公司版本
        Integer feeType = businessRuleUserPermissionHelp.getFeeType(corpid);
        FormClueJointRecheckAllRuleVO formClueJointRecheckAllRuleVO = new FormClueJointRecheckAllRuleVO();
        List<ClueJointRecheckRulePojo> clueJointRecheckRulePojoList = new ArrayList<>();
        try{
            ClueJointRecheckRulePojo customerRule = new ClueJointRecheckRulePojo();
            ClueJointRecheckRulePojo contactRule = new ClueJointRecheckRulePojo();
           //从数据库中获得规则数据
           List<ClueJointRecheckEntity> clueJointRecheckEntityList = clueJointRecheckModel.getByFormId(formId, corpid);
           if (CollectionsUtil.isEmpty(clueJointRecheckEntityList)){
               //没有数据代表是第一次点击进入，给与默认数据
               customerRule.setType(BasicConstant.ONE);
               customerRule.setEnable(BasicConstant.ZERO);
               customerRule.setName(StringConstant.CUSTOMER);
               customerRule.setRuleList(new JSONArray());

               contactRule.setType(BasicConstant.TWO);
               contactRule.setEnable(BasicConstant.ZERO);
               contactRule.setName(StringConstant.CONTACT);
               contactRule.setRuleList(new JSONArray());

           }else{
               //数据库中有数据
               // 修复45552 【查重】联合查重设置之后无法保存设置
               if (Objects.equals(BasicConstant.ONE, clueJointRecheckEntityList.size())){
                   ClueJointRecheckEntity clueJointRecheckEntity = clueJointRecheckEntityList.get(0);
                   //说明其中一条数据为null，没有插入到数据库
                   if (Objects.equals(BasicConstant.ONE, clueJointRecheckEntity.getType())){
                       //客户,给联系人赋予默认值
                       contactRule.setType(BasicConstant.TWO);
                       contactRule.setEnable(BasicConstant.ZERO);
                       contactRule.setName(StringConstant.CONTACT);
                       contactRule.setRuleList(new JSONArray());
                   }else if (Objects.equals(BasicConstant.TWO, clueJointRecheckEntity.getType())){
                       //联系人，给客户赋予默认值
                       customerRule.setType(BasicConstant.ONE);
                       customerRule.setEnable(BasicConstant.ZERO);
                       customerRule.setName(StringConstant.CUSTOMER);
                       customerRule.setRuleList(new JSONArray());
                   }
               }
               for (ClueJointRecheckEntity clueJointRecheckEntity : clueJointRecheckEntityList){
                   //获得客户数据   1代表客户；2代表联系人'
                   if (Objects.equals(BasicConstant.ONE, clueJointRecheckEntity.getType())){
                       //是客户数据
                       //判断客户是否开启   0代表没有开启，1代表开启
                       String rules = clueJointRecheckEntity.getRules();
                       JSONArray jsonArray = JSONArray.parseArray(rules);
                       customerRule.setType(BasicConstant.ONE);
                       customerRule.setEnable(clueJointRecheckEntity.getEnable());
                       customerRule.setName(StringConstant.CUSTOMER);
                       //高级版特殊处理
//                       if(Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType)){
//                           List<RecheckRuleFromDbPojo> recheckRuleFromDbPojoList = jsonArray.toJavaList(RecheckRuleFromDbPojo.class);
//                           //将不是名称和电话字段的规则移除
//                           recheckRuleFromDbPojoList.removeIf(item -> !Objects.equals(CustomerManagementEnum.NAME.getAttr(), item.getAttr()) &&
//                                   !Objects.equals(CustomerManagementEnum.PHONE.getAttr() + "." + "text_2", item.getAttr()));
//                           jsonArray = JSONArray.parseArray(JSONObject.toJSONString(recheckRuleFromDbPojoList));
//                       }
                       customerRule.setRuleList(jsonArray);
                   }else if (Objects.equals(BasicConstant.TWO, clueJointRecheckEntity.getType())){
                       //获得联系人数据
                       //判断联系人是否开启   0代表没有开启，1代表开启
                       String rules = clueJointRecheckEntity.getRules();
                       JSONArray jsonArray = JSONArray.parseArray(rules);
                       List<RecheckRuleFromDbPojo> recheckRuleFromDbPojoList = jsonArray.toJavaList(RecheckRuleFromDbPojo.class);
                       for (RecheckRuleFromDbPojo recheckRuleFromDbPojo : recheckRuleFromDbPojoList){
                           recheckRuleFromDbPojo.setFormId(null);
                       }
                       jsonArray = JSONArray.parseArray(JSONObject.toJSONString(recheckRuleFromDbPojoList));
                       contactRule.setType(BasicConstant.TWO);
                       contactRule.setEnable(clueJointRecheckEntity.getEnable());
                       contactRule.setName(StringConstant.CONTACT);
                       //高级版特殊处理
//                       if(Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType)){
//                           List<RecheckRuleFromDbPojo> recheckRuleFromDbPojoList = jsonArray.toJavaList(RecheckRuleFromDbPojo.class);
//                           //将不是名称和电话字段的规则移除
//                           recheckRuleFromDbPojoList.removeIf(item -> !Objects.equals(ContactEnum.NAME.getAttr(), item.getAttr()) &&
//                                   !Objects.equals(ContactEnum.PHONE.getAttr() + "." + "text_2", item.getAttr()));
//                           jsonArray = JSONArray.parseArray(JSONObject.toJSONString(recheckRuleFromDbPojoList));
//                       }
                       contactRule.setRuleList(jsonArray);
                   }
               }
           }
            clueJointRecheckRulePojoList.add(customerRule);
            clueJointRecheckRulePojoList.add(contactRule);
            formClueJointRecheckAllRuleVO.setSettings(clueJointRecheckRulePojoList);
       }catch (Exception e){
           LOGGER.error("ClueJointRechekServiceImpl.get出错：", e);
           throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
       }
        return formClueJointRecheckAllRuleVO;
    }

    /**
     * 获得联系人的关联字段
     * @param recheckRuleFromDbPojo
     * @param corpid
     * @return
     * @throws XbbException
     */
    public RecheckJointLinkAttrPojo getContactAttr(RecheckRuleFromDbPojo recheckRuleFromDbPojo, String corpid) throws XbbException{
        FormClueJointRecheckDTO formClueJointRecheckDTO = new FormClueJointRecheckDTO();
        formClueJointRecheckDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
        formClueJointRecheckDTO.setCorpid(corpid);
        List<ClueRecheckFormPojo> template = getTemplate(formClueJointRecheckDTO);
        if (CollectionsUtil.isNotEmpty(template)){
            Long linkFormId = template.get(0).getFormId();
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(linkFormId, corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            explainList.forEach(item -> explainMap.put(item.getAttr(), item));
            String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
            FieldAttrEntity fieldAttrEntity = explainMap.get(linkAttr);
            if (Objects.nonNull(fieldAttrEntity)){
                RecheckJointLinkAttrPojo clueRecheckContactAttrPojo = new RecheckJointLinkAttrPojo();
                clueRecheckContactAttrPojo.setAttr(linkAttr);
                clueRecheckContactAttrPojo.setAttrName(fieldAttrEntity.getAttrName());
                clueRecheckContactAttrPojo.setFieldId(fieldAttrEntity.getFieldId());
                clueRecheckContactAttrPojo.setFieldType(fieldAttrEntity.getFieldType());
                clueRecheckContactAttrPojo.setIsRedundant(fieldAttrEntity.getIsRedundant());
                return clueRecheckContactAttrPojo;
            }
        }

        return null;
    }

    /**
     * 获得关联客户的线索字段
     * @param recheckRuleFromDbPojo
     * @param corpid
     * @return
     * @throws XbbException
     */
    public RecheckJointClueAttrPojo getClueAttr(RecheckRuleFromDbPojo recheckRuleFromDbPojo, String corpid, Long formId) throws XbbException{
        //获得关联的线索规则
        try{
            String clueAttr = recheckRuleFromDbPojo.getAttr();
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> clueExplainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            HashMap<String, FieldAttrEntity> clueExplainMap = new HashMap<>(clueExplainList.size());
            clueExplainList.forEach(item -> clueExplainMap.put(item.getAttr(), item));
            FieldAttrEntity clueFieldAttrEntity = clueExplainMap.get(clueAttr);
            if (Objects.nonNull(clueFieldAttrEntity)){
                RecheckJointClueAttrPojo recheckJointClueAttrPojo = new RecheckJointClueAttrPojo();
                recheckJointClueAttrPojo.setClueAttr(clueAttr);
                recheckJointClueAttrPojo.setClueAttrName(clueFieldAttrEntity.getAttrName());
                recheckJointClueAttrPojo.setFieldId(clueFieldAttrEntity.getFieldId());
                recheckJointClueAttrPojo.setFieldType(clueFieldAttrEntity.getFieldType());
                recheckJointClueAttrPojo.setIsRedundant(clueFieldAttrEntity.getIsRedundant());
                return recheckJointClueAttrPojo;
            }
           return null;
        }catch (Exception e){
            LOGGER.error("ClueJointRechekServiceImpl.getClueAttr出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
    }

    /**
     * 获得所有的客户可选字段
     * @param clueJointRecheckCustomerAttrDTO
     * @return
     */
    @Override
    public ClueJointRecheckCustomerAttrVO getAllCustomerAttr(ClueJointRecheckCustomerAttrDTO clueJointRecheckCustomerAttrDTO) throws XbbException{
        Long customerFormId = clueJointRecheckCustomerAttrDTO.getCustomerFormId();
        Integer businessType = clueJointRecheckCustomerAttrDTO.getBusinessType();
        Integer isAll = clueJointRecheckCustomerAttrDTO.getIsAll();
        String corpid = clueJointRecheckCustomerAttrDTO.getCorpid();
        ClueJointRecheckCustomerAttrVO clueJointRecheckCustomerAttrVO = new ClueJointRecheckCustomerAttrVO();
        try{
            List<RecheckJointLinkAttrPojo> customerAttrPojoArrayList = new ArrayList<>();
            //1代表是全部模板，0代表不是全部模板
           if (Objects.equals(BasicConstant.ONE, isAll)){
               HashMap<String, FieldAttrEntity> explainMap = getCustomerAllTemplate(clueJointRecheckCustomerAttrDTO);
               Collection<FieldAttrEntity> values = explainMap.values();
               for (FieldAttrEntity customFieldAttrEntity : values){
                   //添加子表单单行文本判断
                   boolean flag = Objects.nonNull(customFieldAttrEntity) && (Objects.equals(customFieldAttrEntity.getFieldType(),FieldTypeEnum.SUB_FORM.getType())
                           ||  Objects.equals(customFieldAttrEntity.getFieldType(), FieldTypeEnum.CONTACT_NUMBER.getType()));
                   if (flag) {
                       SubFormPoJo subForm = customFieldAttrEntity.getSubForm();
                       if (Objects.nonNull(subForm) && CollectionsUtil.isNotEmpty(subForm.getItems())) {
                           List<? extends FieldAttrEntity> items = subForm.getItems();
                           for (FieldAttrEntity item : items) {
                               boolean textFlag = Objects.equals(item.getIsOpen(),BasicConstant.ONE) && Objects.equals(item.getFieldType(),FieldTypeEnum.TEXT.getType());
                               if (textFlag) {
                                   RecheckJointLinkAttrPojo customerAttrPojo = new RecheckJointLinkAttrPojo();
                                   customerAttrPojo.setFieldId(item.getFieldId());
                                   customerAttrPojo.setAttr(customFieldAttrEntity.getAttr() + "." + item.getAttr());
                                   String defaultName = customFieldAttrEntity.getDefaultName();
                                   if (StringUtils.isEmpty(defaultName)){
                                       defaultName = customFieldAttrEntity.getAttrName();
                                   }
                                   customerAttrPojo.setAttrName(defaultName  + "." + item.getAttrName());
                                   customerAttrPojo.setIsRedundant(item.getIsRedundant());
                                   customerAttrPojo.setFieldType(item.getFieldType());
                                   customerAttrPojoArrayList.add(customerAttrPojo);
                               }
                           }
                       }
                   }else{
                       RecheckJointLinkAttrPojo customerAttrPojo = new RecheckJointLinkAttrPojo();
                       customerAttrPojo.setAttr(customFieldAttrEntity.getAttr());
                       String defaultName = customFieldAttrEntity.getDefaultName();
                       if (StringUtils.isEmpty(defaultName)){
                           defaultName = customFieldAttrEntity.getAttrName();
                       }
                       customerAttrPojo.setAttrName(defaultName);
                       customerAttrPojo.setIsRedundant(customFieldAttrEntity.getIsRedundant());
                       customerAttrPojo.setFieldId(customFieldAttrEntity.getFieldId());
                       customerAttrPojo.setFieldType(customFieldAttrEntity.getFieldType());
                       customerAttrPojoArrayList.add(customerAttrPojo);
                   }
               }
           }else if (Objects.equals(BasicConstant.ZERO, isAll)){
               if (Objects.nonNull(customerFormId)){
                   //单个模版
                   PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(customerFormId, corpid);
                   if (Objects.isNull(paasFormExplainEntity)) {
                       throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                   }
                   List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                   HashMap<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
                   explainList.forEach(item -> explainMap.put(item.getAttr(), item));
                   List<Integer> clueJointRecheckAttr = getClueJointRecheckAttr();
                   //不符合条件字段类型移除移除
                   //将隐藏字段去除
                   //处于回收站或未启用移除
                   explainList.removeIf(item -> !clueJointRecheckAttr.contains(item.getFieldType()) ||
                           Objects.equals(BasicConstant.ONE, item.getEditHide()) ||
                           Objects.equals(BasicConstant.ZERO, item.getIsOpen()) ||
                           Objects.equals(BasicConstant.TWO, item.getIsOpen()));
                   customerAttrPojoArrayList = clueAndContactResultDeal(explainList, businessType);
               }
           }
           clueJointRecheckCustomerAttrVO.setCustomerAttrList(customerAttrPojoArrayList);
           return clueJointRecheckCustomerAttrVO;
       }catch (Exception e){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
       }
    }


    /**
     * 获得客户全部模板的解释合集
     * @param clueJointRecheckCustomerAttrDTO
     * @return
     */
    private HashMap<String, FieldAttrEntity> getCustomerAllTemplate(ClueJointRecheckCustomerAttrDTO clueJointRecheckCustomerAttrDTO) throws XbbException{
        //全部模版
        List<ClueRecheckFormPojo> clueRecheckFormPojoList = new ArrayList<>();
        Map<String, Object> map = BeanUtil.convertBean2Map(clueJointRecheckCustomerAttrDTO,true);
        map.put("del",DelEnum.NORMAL.getDel());
        map.put("hidden", 0);
        map.put("enable", 1);
        map.put("distributorMark", 0);
        map.remove("clueFormId");
        map.remove("customerFormId");
        map.remove("isAll");
        map.remove("clueAttr");
        //获得客户的所有处于启用状态的模版
        List<PaasFormEntityExt> paasFormEntityList = paasFormModel.list(map);
        if (CollectionsUtil.isEmpty(paasFormEntityList)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        //获得所有表单模版的解释，对所有表单模版的系统字段取合集
        Map<String, Object> formExplainMap = BeanUtil.convertBean2Map(clueJointRecheckCustomerAttrDTO, true);
        List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(formExplainMap);
        if (formExplainList.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        //将处于未启用状态的表单解释移除
        List<Long> formIdList = new ArrayList<>();
        paasFormEntityList.forEach(item -> formIdList.add(item.getId()));
        formExplainList.removeIf(item -> !formIdList.contains(item.getFormId()));
        //遍历解释取解释的合集
        List<FieldAttrEntity> allExplainList = new ArrayList<>();
        for (PaasFormExplainEntity paasFormExplainEntity : formExplainList){
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            List<Integer> clueJointRecheckAttr = getClueJointRecheckAttr();
            //除单行文本、子表单外类型移除
            //非系统字段移除
            //isRedundant                               1：自定义字段；0：系统字段
            //将隐藏字段去除
            //处于回收站或未启用移除
            //全部模版将外链的拓展字段移除
            explainList.removeIf(item -> !clueJointRecheckAttr.contains(item.getFieldType()) ||
                    Objects.equals(BasicConstant.ONE, item.getIsRedundant()) ||
                    Objects.equals(BasicConstant.ONE, item.getEditHide()) ||
                    Objects.equals(BasicConstant.ZERO, item.getIsOpen()) ||
                    Objects.equals(BasicConstant.TWO, item.getIsOpen()) ||
                    Objects.equals("extensionField", item.getSaasAttr()));

            allExplainList.addAll(explainList);
        }
        HashMap<String, FieldAttrEntity> explainMap = new HashMap<>(allExplainList.size());
        allExplainList.forEach(item -> explainMap.put(item.getAttr(), item));
        return explainMap;
    }

   /**
     * 获得关联的客户字段
     * @param recheckRuleFromDbPojo
     * corpid
     * @return
     */
    public ClueJointRecheckCustomerAndContactPojo getCustomerAttr(RecheckRuleFromDbPojo recheckRuleFromDbPojo, String corpid) throws XbbException{
        RecheckJointLinkAttrPojo recheckJointLinkAttrPojo = new RecheckJointLinkAttrPojo();
        ClueRecheckFormPojo clueRecheckFormPojo = new ClueRecheckFormPojo();
        ClueJointRecheckCustomerAndContactPojo clueJointRecheckCustomerRulePojo = new ClueJointRecheckCustomerAndContactPojo();
        try{
           //获得关联的attr
           String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
           //判断是否是关联了全部模版   1代表是全部模板，0代表不是全部模板
           if (Objects.equals(BasicConstant.ONE, recheckRuleFromDbPojo.getIsAll())){
               //全部模版
               CustomerManagementEnum customerManagementEnum = CustomerManagementEnum.getAttrName(linkAttr);
               recheckJointLinkAttrPojo.setAttr(linkAttr);
               recheckJointLinkAttrPojo.setAttrName(customerManagementEnum.getAttrName());
               recheckJointLinkAttrPojo.setFieldType(customerManagementEnum.getFieldType());
               recheckJointLinkAttrPojo.setIsRedundant(BasicConstant.ZERO);
               clueJointRecheckCustomerRulePojo.setLinkAttr(recheckJointLinkAttrPojo);
               //模版字段返回
               clueRecheckFormPojo.setFormId(null);
               clueRecheckFormPojo.setFormName(OperateModuleTypeEnum.DUPLICATE_ALL_TEMPLATE.getName());
               clueRecheckFormPojo.setIsAll(BasicConstant.ONE);
               clueJointRecheckCustomerRulePojo.setForm(clueRecheckFormPojo);

               return clueJointRecheckCustomerRulePojo;
           }else if (Objects.equals(BasicConstant.ZERO, recheckRuleFromDbPojo.getIsAll())){
               //不是全部模版
               //获得关联的formId
               Long linkFormId = recheckRuleFromDbPojo.getFormId();
               PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(linkFormId, corpid);
               if (Objects.isNull(paasFormExplainEntity)) {
                   throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
               }
               List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
               Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
               explainList.forEach(item -> explainMap.put(item.getAttr(), item));
               FieldAttrEntity fieldAttrEntity = explainMap.get(linkAttr);
               if (Objects.nonNull(fieldAttrEntity)){
                   recheckJointLinkAttrPojo.setAttr(linkAttr);
                   recheckJointLinkAttrPojo.setFieldId(fieldAttrEntity.getFieldId());
                   recheckJointLinkAttrPojo.setAttrName(fieldAttrEntity.getAttrName());
                   recheckJointLinkAttrPojo.setFieldType(fieldAttrEntity.getFieldType());
                   recheckJointLinkAttrPojo.setIsRedundant(fieldAttrEntity.getIsRedundant());
                   clueJointRecheckCustomerRulePojo.setLinkAttr(recheckJointLinkAttrPojo);
               }
               //客户模版返回
               PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(linkFormId, corpid);
               if (Objects.isNull(paasFormEntityExt)){
                   throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
               }
               clueRecheckFormPojo.setFormId(linkFormId);
               clueRecheckFormPojo.setFormName(paasFormEntityExt.getName());
               clueRecheckFormPojo.setBusinessType(paasFormEntityExt.getBusinessType());
               clueRecheckFormPojo.setIsAll(BasicConstant.ZERO);
               clueJointRecheckCustomerRulePojo.setForm(clueRecheckFormPojo);
               return clueJointRecheckCustomerRulePojo;
           }
       }catch(Exception e){
           throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
       }
        return null;
    }

    /**
     * 联合查重的规则保存
     * @param formClueJointRecheckSaveDTO
     * @return
     * @throws XbbException
     */
    @Override
    public BaseVO save(FormClueJointRecheckSaveDTO formClueJointRecheckSaveDTO) throws XbbException {
        Long formId = formClueJointRecheckSaveDTO.getFormId();
        String corpid = formClueJointRecheckSaveDTO.getCorpid();
        String userName = formClueJointRecheckSaveDTO.getLoginUserName();
        String userId = formClueJointRecheckSaveDTO.getUserId();
        String httpHeader = formClueJointRecheckSaveDTO.getHttpHeader();
        BaseVO baseVO = new BaseVO();
        List<DetailLogPojo> detailArr = new ArrayList<>();
        List<ClueRecheckJointRulePojo> saveRuleList = formClueJointRecheckSaveDTO.getSaveRuleList();
        if (CollectionsUtil.isEmpty(saveRuleList)){
            //传入的规则为空
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.RULE_CANNOT_BE_EMPTY);
        }
        //对高级版的公司添加保存校验，规则只能是名称对应名称，电话对应电话
        //获得公司版本
        Integer feeType = businessRuleUserPermissionHelp.getFeeType(corpid);
        if(Objects.equals(PackageTypeEnum.ADVANCED.getType(), feeType)){
            for (ClueRecheckJointRulePojo clueRecheckJointRule : saveRuleList){
                // 1代表客户；2代表联系人
                List<RecheckRuleFromDbPojo> ruleList = clueRecheckJointRule.getRuleList();
                if (CollectionsUtil.isNotEmpty(ruleList)){
                    long count = ruleList.stream().distinct().count();
                    int distinctCount = Integer.parseInt(String.valueOf(count));
                    if (!Objects.equals(ruleList.size(), distinctCount)){
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.RULES_MUST_CORRESPOND);
                    }
                }
            }
        }
        //根据formId查找表单信息
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        //根据formId去数据库中查询数据，判断是更新还是插入操作
        List<ClueJointRecheckEntity> clueJointRecheckEntityList = clueJointRecheckModel.getByFormId(formId, corpid);
        Long oldUpdataTime = DateTimeUtil.getLong()/1000 - 60;
        if(CollectionsUtil.isEmpty(clueJointRecheckEntityList)){
            //插入操作
            for (ClueRecheckJointRulePojo clueRecheckJointRule : saveRuleList){
                // 1代表客户；2代表联系人
                Integer type = clueRecheckJointRule.getType();
                //0代表没有开启，1代表开启
                Integer enable = clueRecheckJointRule.getEnable();
                int customerBusinessType = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
                int contactBusinessType = XbbRefTypeEnum.CONTACT.getCode();

                DuplicateClueLinkPojo duplicateClueLinkPojo = new DuplicateClueLinkPojo();
                duplicateClueLinkPojo.setCorpid(corpid);
                duplicateClueLinkPojo.setOperation(OperateTypeEnum.NEW.getAlias());
                duplicateClueLinkPojo.setFormId(formId);
                duplicateClueLinkPojo.setOldUpdateTime(oldUpdataTime);
                //插入操作
                //是客户
                if (Objects.equals(BasicConstant.ONE, type)) {
                    insertRule(clueRecheckJointRule, customerBusinessType, formClueJointRecheckSaveDTO);
                    // 记录日志
                    duplicateClueLinkPojo.setLinkBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                    duplicateClueLinkPojo.setNewObj(clueRecheckJointRule);
                    detailArr = logHelp.log4ClueLink(duplicateClueLinkPojo, detailArr);
//                    if (Objects.nonNull(paasFormEntityExt)){
//                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
//                        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
//                                paasFormEntityExt.getName(), memo, httpHeader);
//                    }
                } else if (Objects.equals(BasicConstant.TWO, type)){
                    //是联系人
                    insertRule(clueRecheckJointRule, contactBusinessType, formClueJointRecheckSaveDTO);
                    //记录日志
                    duplicateClueLinkPojo.setLinkBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                    duplicateClueLinkPojo.setNewObj(clueRecheckJointRule);
//                    //根据formId查找表单信息
//                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
                    detailArr = logHelp.log4ClueLink(duplicateClueLinkPojo, detailArr);
//                    if (Objects.nonNull(paasFormEntityExt)){
//                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
//                        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
//                                paasFormEntityExt.getName(), memo, httpHeader);
//                    }
                }
            }
            long newUpdateTime = DateTimeUtil.getLong()/1000;
            detailArr = logHelp.log4UpdateTimeDuplicate(detailArr, null, oldUpdataTime, newUpdateTime);
            if (Objects.nonNull(paasFormEntityExt)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
                        paasFormEntityExt.getName(), memo, httpHeader);
            }
        }else {
            //更新操作
            for (ClueRecheckJointRulePojo clueRecheckJointRule : saveRuleList){
                // 1代表客户；2代表联系人
                Integer type = clueRecheckJointRule.getType();
                //0代表没有开启，1代表开启
                Integer enable = clueRecheckJointRule.getEnable();
                List<RecheckRuleFromDbPojo> ruleListAttr = clueRecheckJointRule.getRuleList();

                DuplicateClueLinkPojo duplicateClueLinkPojo = new DuplicateClueLinkPojo();
                duplicateClueLinkPojo.setCorpid(corpid);
                duplicateClueLinkPojo.setOperation(OperateTypeEnum.EDIT.getAlias());
                duplicateClueLinkPojo.setFormId(formId);

                ClueJointRecheckEntity clueJointRecheckEntity = new ClueJointRecheckEntity();
                if (Objects.equals(BasicConstant.ONE, type)) {
                    //是客户
                    //判断是否有规则，开启的状态下规则不允许为空
                    if (Objects.equals(BasicConstant.ONE, enable) && CollectionsUtil.isEmpty(ruleListAttr)){
                        throw new XbbException(ProErrorCodeEnum.API_ERROR_260056);
                    }
                    if (Objects.equals(BasicConstant.ONE, enable)){
                        //只有是开启状态下才需要判断，关闭状态下任何形式都可以保存
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                            //判断是否有的数据为空
                            String attr = recheckRuleFromDbPojo.getAttr();
                            String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
                            Long customerFormId = recheckRuleFromDbPojo.getFormId();
                            Integer isAll = recheckRuleFromDbPojo.getIsAll();
                            boolean flag = Objects.isNull(attr) || Objects.isNull(linkAttr) || (Objects.equals(BasicConstant.ZERO, isAll) && Objects.isNull(customerFormId));
                            if (flag){
                                throw new XbbException(ProErrorCodeEnum.API_ERROR_260057);
                            }
                        }
                    }
                    //判断关联的规则数是否超过3个
                    if(ruleListAttr.size() > BasicConstant.THREE){
                        throw new XbbException(ProErrorCodeEnum.API_ERROR_260055);
                    }
                    for (ClueJointRecheckEntity clueJointRecheckEntity1 : clueJointRecheckEntityList){
                        if (Objects.equals(clueJointRecheckEntity1.getType(), BasicConstant.ONE)){
                            duplicateClueLinkPojo.setOldUpdateTime(clueJointRecheckEntity1.getUpdateTime());
                            duplicateClueLinkPojo.setOldEnable(clueJointRecheckEntity1.getEnable());
                            duplicateClueLinkPojo.setOldRules(clueJointRecheckEntity1.getRules());
                        }
                    }
                    clueJointRecheckEntity.setType(type);
                    clueJointRecheckEntity.setEnable(enable);
                    clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                    clueJointRecheckEntity.setCorpid(corpid);
                    clueJointRecheckEntity.setFormId(formId);
                    clueJointRecheckModel.update(clueJointRecheckEntity);
                    //记录日志
                    duplicateClueLinkPojo.setLinkBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                    duplicateClueLinkPojo.setNewObj(clueRecheckJointRule);
                    //根据formId查找表单信息
//                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
                    detailArr = logHelp.log4ClueLink(duplicateClueLinkPojo, detailArr);
//                    if (Objects.nonNull(paasFormEntityExt)){
//                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
//                        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
//                                paasFormEntityExt.getName(), memo, httpHeader);
//                    }

                } else if (Objects.equals(BasicConstant.TWO, type)){
                    FormClueJointRecheckDTO formClueJointRecheckDTO = new FormClueJointRecheckDTO();
                    formClueJointRecheckDTO.setCorpid(formClueJointRecheckSaveDTO.getCorpid());
                    formClueJointRecheckDTO.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                    List<ClueRecheckFormPojo> contactTemplate = new ArrayList<>();
                    formClueJointRecheckDTO.setDistributorMark(0);
                    contactTemplate = getTemplate(formClueJointRecheckDTO);
                    //判断是否有规则，开启的状态下规则不允许为空
                    if (Objects.equals(BasicConstant.ONE, enable) && CollectionsUtil.isEmpty(ruleListAttr)){
                        throw new XbbException(ProErrorCodeEnum.API_ERROR_260056);
                    }
                    if (Objects.equals(BasicConstant.ZERO, enable) && CollectionsUtil.isNotEmpty(ruleListAttr)){
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                            recheckRuleFromDbPojo.setFormId(contactTemplate.get(0).getFormId());
                        }
                    }
                    if (Objects.equals(BasicConstant.ONE, enable)){
                        //只有是开启状态下才需要判断，关闭状态下任何形式都可以保存
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                            //判断是否有的数据为空
                            String attr = recheckRuleFromDbPojo.getAttr();
                            String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
                            recheckRuleFromDbPojo.setFormId(contactTemplate.get(0).getFormId());
                            boolean flag = Objects.isNull(attr) || Objects.isNull(linkAttr);
                            if (flag){
                                throw new XbbException(ProErrorCodeEnum.API_ERROR_260057);
                            }
                        }
                    }
                    //判断关联的规则数是否超过3个
                    if(ruleListAttr.size() > BasicConstant.THREE){
                        throw new XbbException(ProErrorCodeEnum.API_ERROR_260055);
                    }
                    for (ClueJointRecheckEntity clueJointRecheckEntity1 : clueJointRecheckEntityList){
                        if (Objects.equals(clueJointRecheckEntity1.getType(), BasicConstant.TWO)){
                            oldUpdataTime = clueJointRecheckEntity1.getUpdateTime();
                            duplicateClueLinkPojo.setOldUpdateTime(oldUpdataTime);
                            duplicateClueLinkPojo.setOldEnable(clueJointRecheckEntity1.getEnable());
                            duplicateClueLinkPojo.setOldRules(clueJointRecheckEntity1.getRules());
                        }
                    }
                    //是联系人
                    clueJointRecheckEntity.setCorpid(corpid);
                    clueJointRecheckEntity.setFormId(formId);
                    clueJointRecheckEntity.setType(type);
                    clueJointRecheckEntity.setEnable(enable);
                    clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                    clueJointRecheckModel.update(clueJointRecheckEntity);
                    //记录日志
                    duplicateClueLinkPojo.setLinkBusinessType(XbbRefTypeEnum.CONTACT.getCode());
                    duplicateClueLinkPojo.setNewObj(clueRecheckJointRule);
                    //根据formId查找表单信息
//                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
                    detailArr = logHelp.log4ClueLink(duplicateClueLinkPojo, detailArr);
//                    if (Objects.nonNull(paasFormEntityExt)){
//                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
//                        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
//                                paasFormEntityExt.getName(), memo, httpHeader);
//                    }
                }
            }
            long newUpdateTime = DateTimeUtil.getLong()/1000;
            detailArr = logHelp.log4UpdateTimeDuplicate(detailArr, null, oldUpdataTime, newUpdateTime);
            if (Objects.nonNull(paasFormEntityExt)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DUPLICATE_JOINT_UPDATE_FORM), userName, paasFormEntityExt.getName());
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, formId.toString(),
                        paasFormEntityExt.getName(), memo, httpHeader);
            }
        }
        return baseVO;
    }

    /**
     * 将保存的规则插入数据库
     * @param
     */
    public void insertRule(ClueRecheckJointRulePojo clueRecheckJointRule, Integer linkBusinessType, FormClueJointRecheckSaveDTO formClueJointRecheckSaveDTO) throws XbbException{
        Long formId = formClueJointRecheckSaveDTO.getFormId();
        String corpid = formClueJointRecheckSaveDTO.getCorpid();
        Integer businessType = formClueJointRecheckSaveDTO.getBusinessType();
            //0代表没有开启，1代表开启
            Integer enable = clueRecheckJointRule.getEnable();
            List<RecheckRuleFromDbPojo> ruleListAttr = clueRecheckJointRule.getRuleList();
            //插入操作
            ClueJointRecheckEntity clueJointRecheckEntity = new ClueJointRecheckEntity();
            clueJointRecheckEntity.setBusinessType(businessType);
            clueJointRecheckEntity.setFormId(formId);
            clueJointRecheckEntity.setCorpid(corpid);
            clueJointRecheckEntity.setDel(DelEnum.NORMAL.getDel());
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(linkBusinessType);
            switch(xbbRefTypeEnum){
                case CUSTOMER_MANAGEMENT:
                    //是客户
                    //判断是否开启线索联合客户查重  0代表没有开启，1代表开启
                    if (Objects.equals(BasicConstant.ZERO, enable)){
                        //没有开启
                        clueJointRecheckEntity.setType(BasicConstant.ONE);
                        clueJointRecheckEntity.setEnable(enable);
                        clueJointRecheckEntity.setLinkBusinessType(linkBusinessType);
                        clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                        clueJointRecheckModel.insert(clueJointRecheckEntity);

                        //添加日志

                    }else if (Objects.equals(BasicConstant.ONE, enable)){
                        //开启
                        //判断是否有规则，开启的状态下规则不允许为空
                        if (CollectionsUtil.isEmpty(ruleListAttr)){
                            throw new XbbException(ProErrorCodeEnum.API_ERROR_260056);
                        }
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                            //判断是否有的数据为空
                            String attr = recheckRuleFromDbPojo.getAttr();
                            String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
                            Long customerFormId = recheckRuleFromDbPojo.getFormId();
                            Integer isAll = recheckRuleFromDbPojo.getIsAll();
                            boolean flag = Objects.isNull(attr) || Objects.isNull(linkAttr) || (Objects.equals(BasicConstant.ZERO, isAll) && Objects.isNull(customerFormId));
                            if (flag){
                                throw new XbbException(ProErrorCodeEnum.API_ERROR_260057);
                            }
                        }
                        //判断关联的规则数是否超过3个
                        if(ruleListAttr.size() > BasicConstant.THREE){
                            throw new XbbException(ProErrorCodeEnum.API_ERROR_260055);
                        }
                        clueJointRecheckEntity.setType(BasicConstant.ONE);
                        clueJointRecheckEntity.setEnable(enable);
                        clueJointRecheckEntity.setLinkBusinessType(linkBusinessType);
                        clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                        clueJointRecheckModel.insert(clueJointRecheckEntity);
                    }
                    break;
                case CONTACT:
                    //是联系人
                    //获得联系人的处于开启状态的formId
                    FormClueJointRecheckDTO formClueJointRecheckDTO = new FormClueJointRecheckDTO();
                    formClueJointRecheckDTO.setCorpid(formClueJointRecheckSaveDTO.getCorpid());
                    formClueJointRecheckDTO.setBusinessType(linkBusinessType);
                    List<ClueRecheckFormPojo> contactTemplate = new ArrayList<>();
                    contactTemplate = getTemplate(formClueJointRecheckDTO);
                    //判断是否开启线索联合联系人查重
                    if (Objects.equals(BasicConstant.ZERO, enable)){
                        if (CollectionsUtil.isNotEmpty(ruleListAttr)){
                            for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                                recheckRuleFromDbPojo.setFormId(contactTemplate.get(0).getFormId());
                            }
                        }
                        //没有开启
                        clueJointRecheckEntity.setType(BasicConstant.TWO);
                        clueJointRecheckEntity.setEnable(enable);
                        clueJointRecheckEntity.setLinkBusinessType(linkBusinessType);
                        clueJointRecheckEntity.setFormId(formId);
                        clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                        clueJointRecheckModel.insert(clueJointRecheckEntity);
                    }else if (Objects.equals(BasicConstant.ONE, enable)){
                        //开启
                        //判断是否有规则，开启的状态下规则不允许为空
                        if (CollectionsUtil.isEmpty(ruleListAttr)){
                            throw new XbbException(ProErrorCodeEnum.API_ERROR_260056);
                        }
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo: ruleListAttr){
                            //判断是否有的数据为空
                            String attr = recheckRuleFromDbPojo.getAttr();
                            String linkAttr = recheckRuleFromDbPojo.getLinkAttr();
                            recheckRuleFromDbPojo.setFormId(contactTemplate.get(0).getFormId());
                            boolean flag = Objects.isNull(attr) || Objects.isNull(linkAttr);
                            if (flag){
                                throw new XbbException(ProErrorCodeEnum.API_ERROR_260057);
                            }
                        }
                        //判断关联的规则数是否超过3个
                        if(ruleListAttr.size() > BasicConstant.THREE){
                            throw new XbbException(ProErrorCodeEnum.API_ERROR_260055);
                        }
                        clueJointRecheckEntity.setType(BasicConstant.TWO);
                        clueJointRecheckEntity.setEnable(enable);
                        clueJointRecheckEntity.setFormId(formId);
                        clueJointRecheckEntity.setLinkBusinessType(linkBusinessType);
                        clueJointRecheckEntity.setRules(JSONArray.toJSONString(ruleListAttr));
                        clueJointRecheckModel.insert(clueJointRecheckEntity);
                    }
                    break;
                default:
                    break;
            }
    }


    @Override
    public Integer update(FormClueJointRecheckDTO formClueJointRecheckDTO) throws XbbException {
        return null;
    }



    @Override
    public Integer delete(Long formId, String corpid) throws XbbException {
        return null;
    }
}
